import { ref, onMounted, onUnmounted, computed } from "vue";
import { filter } from "../util/todoStorage";
const validHash = ["all", "active", "completed"];
export default function useFilter(todoRef) {
  const visibilityRef = ref("all");
  const onHashChange = () => {
    // 得到hash值
    const hash = location.hash.replace(/#\/?/, "");
    if (validHash.includes(hash)) {
      // 有效的hash
      visibilityRef.value = hash;
    } else {
      // 无效的hash
      location.hash = "";
      visibilityRef.value = "all";
    }
  };
  // 1.组件挂载完成的生命周期函数
  onMounted(() => {
    // 监听hash的变化
    window.addEventListener("hashchange", onHashChange);
  });
  // 2.组件销毁过后的生命周期函数
  onUnmounted(() => {
    window.removeEventListener("hashchange", onHashChange);
  });
  const filteredTodoRef = computed(() => {
    return filter(todoRef.value, visibilityRef.value);
  });
  const remainingRef = computed(() => {
    return filter(todoRef.value, "active").length;
  });
  const completed = computed(() => {
    return filter(todoRef.value, "completed").length;
  });
  return { visibilityRef, filteredTodoRef, completed, remainingRef };
}
